using UnityEngine;
using System.Collections;
using System.Linq;
using DanielSig;
using DanielSig.UnityExtensions;

public class Radar : MonoBehaviour
{
	[System.Serializable]
	public class Detection
	{
		public SensationType Type;
		public Transform Target;
		public Vector3 ClosestPoint;
		public float Distance;
	}
	
	[Range(1F,360F)]
	public float FieldOfView;
	[Range(1F,50F)]
	public float Range;
	
	public Detection[] VisibleObjects;
	public LayerMask Mask;
	
	void UpdateSensors()
	{
		Vector3 forward = transform.forward;
		Vector3 center = transform.position;
		float threshold = Mathf.Cos(FieldOfView * Mathf.Deg2Rad / 2);
		var allObjects = from obs in Observable.Observables
							select obs.collider;
		allObjects = from col in allObjects
							where (col.transform.position - center).normalized.Dot(forward) > threshold
							orderby col.transform.position.DistanceToSqr(center)
							select col;
		
		int objCounter = 0;
		foreach(Collider col in allObjects)
		{
			Detection r = VisibleObjects[objCounter++];
			if(objCounter >= VisibleObjects.Length || r.Distance > Range)
				break;
			r.ClosestPoint = col.ClosestPointOnBounds(center);
			r.Distance = center.DistanceTo(r.ClosestPoint);
			r.Target = col.transform;
			r.Type = col.Request<SensationType>("Observation", SensationType.None);
		}
		if(objCounter < VisibleObjects.Length)
		{
			for(int i = objCounter; i < VisibleObjects.Length; i++)
			{
				Detection r = VisibleObjects[i];
				r.Target = null;
				r.Distance = Range;
				r.ClosestPoint = Vector3.zero;
				r.Type = SensationType.None;
			}
		}
	}
	void OnDrawGizmosSelected()
	{
		Gizmos.color = Color.green;
		if(FieldOfView < 360F)
		{
			Vector3 left = transform.forward.RotateY(-FieldOfView / 2);
			Vector3 right = transform.forward.RotateY(FieldOfView / 2);
			Gizmos.DrawRay(transform.position, left * Range);
			Gizmos.DrawRay(transform.position, right * Range);
		}
		
		Gizmos.matrix = Matrix4x4.Scale(new Vector3(1,0,1)) * Gizmos.matrix;
		
		Gizmos.DrawWireSphere(transform.position, Range);
	}
}

